package org.ehe.finance.payable.sched;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.ehe.finance.payable.config.PayableConfig;
import org.ehe.finance.payable.domain.ErpFinancePayable;
import org.ehe.finance.payable.publisher.PayableEventPublisher;
import org.ehe.finance.payable.service.PayableService;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 定时任务
 * @author :zhangnn
 * @className :PayableScheduledTasks
 * @description: TODO
 * @date 2025-09-02 10:44:57
 */

@Slf4j
@Component
@RequiredArgsConstructor
public class PayableScheduledTasks {
    private final PayableService payableService;
    private final PayableEventPublisher eventPublisher;
    private final PayableConfig payableConfig;

    /**
     * 根据配置的时间检查即将到期的应付账款
     */
    @Scheduled(cron = "0 0 ${erp.finance.payable.due-reminder.reminder-hour:9} * * ?")
    public void checkDuePayables() {
        log.info("开始检查即将到期的应付账款...");

        try {
            PayableConfig.DueReminderConfig reminderConfig = payableConfig.getDueReminder();

            // 使用配置中的提醒天数
            int reminderDays = reminderConfig.getDefaultDays();
            List<ErpFinancePayable> duePayables = payableService.getDuePayables(reminderDays);

            for (ErpFinancePayable payable : duePayables) {
                // 发布到期提醒事件
                eventPublisher.publishDueReminder(
                    payable.getId(),
                    payable.getBillNo(),
                    payable.getSupplierId(),
                    payable.getDueDate(),
                    payable.getUnpaidAmount()
                );
            }

            log.info("检查即将到期应付账款完成，共找到 {} 条记录", duePayables.size());

        } catch (Exception e) {
            log.error("检查即将到期应付账款失败", e);
        }
    }

    /**
     * 每月1号更新应付账款统计数据
     */
    @Scheduled(cron = "0 0 1 1 * ?")
    public void updateMonthlyStatistics() {
        log.info("开始更新应付账款月度统计数据...");

        try {
            // 这里可以添加统计数据更新逻辑
            // 例如：更新供应商应付统计、部门应付统计等
            log.info("更新应付账款月度统计数据完成");

        } catch (Exception e) {
            log.error("更新应付账款月度统计数据失败", e);
        }
    }
}
